package com.youlu.campus.service.order;

import cn.hutool.core.collection.CollUtil;
import com.youlu.campus.entity.CaGroupInfo;
import com.youlu.campus.entity.CaInfo;
import com.youlu.campus.entity.OOrderInfo;
import com.youlu.campus.entity.OrderInfo;
import com.youlu.campus.entity.VO.req.OrderUpdateRestReq;
import com.youlu.campus.entity.ca.GiftCaInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName: OrderUpdateRestService
 * @Description: TODO
 * @Author: LiuYun
 * @date: 2023/9/26 上午9:18
 * @Version: V1.0
 */
@RequiredArgsConstructor
@Slf4j
@Service
public class OrderUpdateRestService {

    final MongoTemplate mongoTemplate;

    public void doUpdateRest(OrderUpdateRestReq req) {
        String orderNo = req.getOrderNo();
        String activityId = req.getActivityId();
        String bizType = req.getBizType();
        if (StringUtils.isBlank(activityId)) {
            log.error("订单重置更新参数错误 activityId:{}", activityId);
            return;
        }
        log.info("订单重置更新 start activityId:{}|bizType:{}|orderNo:{}", activityId, bizType, orderNo);
        Query query = new Query();
        query.addCriteria(Criteria.where("activityId").is(activityId));
        query.addCriteria(Criteria.where("taskBizType").is(bizType));
        if (StringUtils.isNotBlank(orderNo)) {
            query.addCriteria(Criteria.where("orderNo").is(orderNo));
        }
        if (CollUtil.isNotEmpty(req.getStatusList())) {
            query.addCriteria(Criteria.where("status").in(req.getStatusList()));
        } else {
            query.addCriteria(Criteria.where("status").nin("0", "6"));
        }
        List<OrderInfo> orderList = this.mongoTemplate.find(query, OrderInfo.class);
        if (CollUtil.isEmpty(orderList)) {
            log.error("订单重置更新 未查询到相关数据 end  activityId:{}|bizType:{}|orderNo:{}", activityId, bizType, orderNo);
            return;
        }
        //获取证书序利
        query = new Query();
        query.addCriteria(Criteria.where("activityId").is(activityId));
        List<CaGroupInfo> groupInfoList = this.mongoTemplate.find(query, CaGroupInfo.class);
        if (CollUtil.isEmpty(groupInfoList)) {
            return;
        }
        CaGroupInfo caGroupInfo = groupInfoList.stream().filter(groupInfo -> groupInfo.getTaskBizType().equals(bizType)).findFirst().orElse(null);
        if (Objects.isNull(caGroupInfo)) {
            return;
        }
        query = new Query();
        query.addCriteria(Criteria.where("activityId").is(activityId));
        query.addCriteria(Criteria.where("caGroupInfoId").is(caGroupInfo.getId()));
        List<CaInfo> caInfoList = this.mongoTemplate.find(query, CaInfo.class);
        if (CollUtil.isEmpty(caInfoList)) {
            return;
        }
        orderList.stream().forEach(orderInfo -> {
            //获取子订单
            Query subQuery = new Query();
            subQuery.addCriteria(Criteria.where("orderNo").is(orderInfo.getOrderNo()));
            List<OOrderInfo> subOrderList = this.mongoTemplate.find(subQuery, OOrderInfo.class);
            update(orderNo,subOrderList,caInfoList);
        });


        log.info("订单重置更新 end activityId:{}|bizType:{}|orderNo:{}", activityId, bizType, orderNo);
    }

    private void update(String orderNo, List<OOrderInfo> subOrderList, List<CaInfo> caInfoList) {
        log.info("订单重置更新 orderNo:{}", orderNo);
        subOrderList.stream().forEach(subOrderInfo -> {
            String itemInfoId = subOrderInfo.getItemInfoId();
            CaInfo caInfo = caInfoList.stream().filter(ca -> itemInfoId.equals(ca.getId())).findFirst().orElse(null);
            if (Objects.isNull(caInfo)) {
                return;
            }
            String title = caInfo.getName();
            String imageUrl = "";
            if (ArrayUtils.isEmpty(caInfo.getCertificateImages())) {
                imageUrl = caInfo.getCertificateImage();
            } else {
                imageUrl = caInfo.getCertificateImages()[0];
            }
            //更新订单封面
            updateOrder(orderNo,title,imageUrl);
            //子订单
             updateSubOrder(subOrderInfo,caInfoList);
        });


    }
     //更新主订单商品封面
    private void updateOrder(String orderNo,String title,String imageUrl) {
        if(StringUtils.isBlank(title)||StringUtils.isBlank(imageUrl)){
            return;
        }
        log.info("订单重置更新 主订单封面更新 orderNo:{}",orderNo);
        Query query = new Query();
        query.addCriteria(Criteria.where("orderNo").is(orderNo));
        Update  update = new Update();
        update.set("imageUrl",imageUrl);
        update.set("title",title);
        update.set("updatedTime",new Date());
        this.mongoTemplate.updateFirst(query,update,OrderInfo.class);
    }

    private void updateSubOrder(OOrderInfo subOrderInfo,List<CaInfo> caInfoList) {
        log.info("订单重置更新 子订单赠品更新 orderNo:{}",subOrderInfo.getOrderNo());
        String itemInfoId = subOrderInfo.getItemInfoId();
        CaInfo caInfo = caInfoList.stream().filter(ca -> itemInfoId.equals(ca.getId())).findFirst().orElse(null);
        if(Objects.isNull(caInfo)){
            return;
        }
        String itemTitle = caInfo.getName();
        String  itemImageUrl = "";
        if (ArrayUtils.isEmpty(caInfo.getCertificateImages())) {
            itemImageUrl = caInfo.getCertificateImage() ;
        } else {
            itemImageUrl = caInfo.getCertificateImages()[0];
        }
        //赠品
        List<GiftCaInfo> giftItems = caInfo.getGiftItems();
        if(CollUtil.isNotEmpty(giftItems)){

        }
        if(StringUtils.isBlank(itemTitle)||StringUtils.isBlank(itemImageUrl)){
            return;
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(subOrderInfo.getId()));
        Update  update = new Update();
        update.set("itemImageUrl",itemImageUrl);
        update.set("itemTitle",itemTitle);
        update.set("caInfo",caInfo);
        update.set("updatedTime",new Date());
        update.set("backUpCaInfo",subOrderInfo.getCaInfo());
        this.mongoTemplate.updateFirst(query,update,OOrderInfo.class);
    }


}
